package com.lzy.srb.sms.controller.api;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.lzy.common.exception.Assert;
import com.lzy.common.result.R;
import com.lzy.common.result.ResponseEnum;
import com.lzy.common.util.RandomUtils;
import com.lzy.common.util.RegexValidateUtils;
import com.lzy.srb.sms.feign.CoreUserInfoClient;
import com.lzy.srb.sms.service.SmsService;
import com.lzy.srb.sms.util.SmsProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/sms")
//@CrossOrigin
@Api("短信管理")
@Slf4j
public class ApiSmsController {

    @Autowired
    SmsService smsService;

    @Autowired
    RedisTemplate redisTemplate;

    @Qualifier("com.lzy.srb.sms.feign.CoreUserInfoClient")
    @Autowired
    CoreUserInfoClient coreUserInfoClient;

    @SentinelResource("sms")
    @ApiOperation("获取验证码")
    @GetMapping("/send/{mobile}")
    public R send(@PathVariable("mobile")String mobile){

        //校验手机号不能为空
        Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);


        //校验手机号合法性
        Assert.isTrue(RegexValidateUtils.checkCellphone(mobile),ResponseEnum.MOBILE_ERROR);

        //判断手机号是否已经注册
        boolean result = coreUserInfoClient.checkMobile(mobile);
        Assert.isTrue(result==false,ResponseEnum.MOBILE_EXIST_ERROR);

        String code = RandomUtils.getFourBitRandom();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", code);
        smsService.send(mobile, SmsProperties.TEMPLATE_CODE,map);

        //将验证码存入redis中
        redisTemplate.opsForValue().set("srb:sms:code:"+mobile,code,2, TimeUnit.MINUTES);

        return R.ok().message("短信发送成功");
    }

}
